#画一个五子棋棋盘
import wx
import boardOperator
import copy
import utl
import time

unit = 50   #棋框
dotnum = 15 #棋线数
# dotnum = 15 #棋线数


# arrayWidth = 10
# arrayHeigh = 10

#棋盘绘制及处理函数
class myFrame(wx.Frame):
    def __init__(self):
        
        self.whiteFlag = 1                      #白棋子标志
        self.blackFlag = 2                      #白棋子标志  
        self.finalWinner = 0                    #最后的胜利者
        self.isEmptyChess = 1                   #是否是空棋盘
        self.unit = unit                        #棋格宽度
        self.dotnum = dotnum                    #棋线
        self.errorWidth = self.unit/2           #棋位误差(点击区域的宽度)
        self.chessFlag = 0                      #棋子颜色标志，双数白，单数黑
        self.boardOperator = boardOperator.boardOperator()  #棋盘算法处理类
        
        super().__init__(parent=None,pos=[100,100],
             size=[self.unit*self.dotnum          #窗口大小
                   +self.unit+20 + 0 ,
                   self.unit*self.dotnum
                   +self.unit+30+20 + 0],
             title="AI五子棋")


        self.Centre()#设置窗口居中

        self.panel = wx.Panel(self)
        self.panel.SetBackgroundColour((220, 210, 0))
        self.panel.Bind(wx.EVT_PAINT,self.draw)
        self.Show()
        #添加鼠标事件  ,将点击事件添加到self.panel上
        self.panel.Bind(wx.EVT_LEFT_DOWN,self.on_left_down)
        # self.panel.Bind(wx.EVT_RIGHT_DOWN,self.on_right_down)


        #鼠标点击事件
    def on_left_down(self,event):  #print('鼠标按下')
        self.play(event.GetPosition())  #传递坐标

    def on_right_down(self,event):    #鼠标右键，添加ai vs  ai
        

        ### ai vs  ai  ####
        while(1):
            black_index = self.boardOperator.getAiIndex(self.blackFlag , 3)    #ai运算 ， 返回一个下标，并下棋#
            self.playChessByIndex(self.blackFlag,black_index)
            winFlag = self.boardOperator.isWinByIndex(self.blackFlag,black_index ,self.boardOperator.getArray()) 
           
            # time.sleep(2)
            if (winFlag):
                print("胜利了")
                self.finalWinner = self.blackFlag
                self.showTap()
                break

            # time.sleep(1)
            white_index = self.boardOperator.getAiIndex(self.whiteFlag , 1)    #ai运算 ， 返回一个下标，并下棋#
            self.playChessByIndex(self.whiteFlag,white_index)
            winFlag = self.boardOperator.isWinByIndex(self.whiteFlag,white_index ,self.boardOperator.getArray()) 
            # time.sleep(2)
            if (winFlag):
                print("胜利了")
                self.finalWinner = self.whiteFlag
                self.showTap()
                break

        ######################
       
       
    # @下棋函数 根据坐标添加图片
    def play(self,pos): 
        #判断坐标，小于或超过棋盘，不做处理
        if (self.boardOperator.isOutOfChessBoard(pos)):  #超出则退出
            print("超过棋盘")
            self.boardOperator.dumpArray()
            return 
        # 计算鼠标点击位置是否在棋子范围
        #矫正鼠标 , 取余
        errorX = pos.x%self.unit
        errorY = pos.y%self.unit
        pos.x = (int)(pos.x/self.unit)*self.unit
        pos.y = (int)(pos.y/self.unit)*self.unit
        # 根据取余 四舍五入
        if(errorX>self.unit/2):
            pos.x = pos.x + self.unit
        if(errorY>self.unit/2):
            pos.y = pos.y + self.unit
        # print("再次次矫正鼠标:","(",pos.x,",",pos.y,")")
        #根据转换坐标是否可下棋
        canplayflag = self.boardOperator.isPosCanPlay(pos)
        if(not canplayflag):
            print("该棋位不可下！")
            return
        #计算该位置是否可下棋子
        # print("棋子最后落地坐标:","(",pos.x - 20,",",pos.y - 20 ,")")
        if(self.chessFlag%2==0):
            # self.playChessByPos(self.whiteFlag,pos)  #下白棋
            self.playChessByPos(self.blackFlag,pos)    #下黑棋
            index = self.boardOperator.translatPosToIndex(pos)
            #判断是否赢了
            winFlag = self.boardOperator.isWinByIndex(self.blackFlag,index ,self.boardOperator.getArray()) 
            if (winFlag):
                print("胜利了")
                self.finalWinner = self.blackFlag
                self.showTap()
                return 
            #########电脑运算################################
            ################################################
            ################################################
            #########################a#######################
            #添加矩阵运算


      
            ai_index = self.boardOperator.getAiIndex(self.whiteFlag , 3)    #ai运算 ， 返回一个下标，并下棋#
            self.playChessByIndex(self.whiteFlag,ai_index)

            winFlag = self.boardOperator.isWinByIndex(self.whiteFlag,ai_index ,self.boardOperator.getArray()) 
            if (winFlag):
                print("胜利了")
                self.finalWinner = self.whiteFlag
                self.showTap()

            ################################################
            ################################################
            ################################################
            ################################################
        else:
            print("已去除人工下子")

    #@下棋函数  根据pos位置
    def playChessByPos(self,flag , pos):
        index = self.boardOperator.translatPosToIndex(pos)
        if(not self.boardOperator.getValueOfArrayByXY(index.x,index.y)==0):
            assert("此处不可下棋子 playChessByPos")
        self.playChessByIndex(flag,index)

    #@下棋函数  根据x,y下标设置
    def playChessByXY(self,flag , x,y):
        if(not self.boardOperator.getValueOfArrayByXY(x,y)==0):
            assert("此处不可下棋子playChessByXY")
        index = utl.pos()
        index.x = x 
        index.y = y
        self.playChessByIndex(flag,index)

    #@下棋函数  根据index下标设置
    def playChessByIndex(self,flag , index):
        if(not self.boardOperator.getValueOfArrayByXY(index.x,index.y)==0):
            assert("此处不可下棋子playChessByIndex")
        pos = self.boardOperator.translatIndexToPos(index)
        if(flag ==self.blackFlag):
            image = wx.Image('image/black.gif', wx.BITMAP_TYPE_GIF)  
            wx.StaticBitmap(self, -1, bitmap=image.ConvertToBitmap(), pos= (pos.x - 20 , pos.y -20 ),size=(200, 200))
        else:
            image = wx.Image('image/white.gif', wx.BITMAP_TYPE_GIF)  
            wx.StaticBitmap(self, -1, bitmap=image.ConvertToBitmap(), pos= (pos.x - 20 , pos.y -20 ),size=(200, 200))
        ################设置标志###################
        self.boardOperator.setBoardFlag( index, flag)       #设置棋子标志数组
        

    #弹框
    def showTap(self ):
        wx.FutureCall(10, self.ShowMessage)
        if (self.finalWinner == self.blackFlag):
            self.SetTitle('Black Chess Is Win!!!')
        else:
            self.SetTitle('White Chess Is Win!!!')
 
    def ShowMessage(self):
        info = "hh"
        if (self.finalWinner == self.blackFlag):
            info = "Black Chess Is Win!!!"
        else:
            info = "White Chess Is Win!!!"
        wx.MessageBox('Win!!!', info, 
            wx.OK | wx.ICON_INFORMATION)

    #param  棋盘绘画函数 
    def draw(self,event):
        mydc=wx.PaintDC(self.panel)
        unit=self.unit
        dotnum=self.dotnum
        x=unit
        y=unit
        #划线横线
        for i in range(1,dotnum+1):
            mydc.DrawLine(x,y,x,unit*dotnum)
            x=x+unit
        #划线竖线
        x=unit
        for i in range(1,dotnum+1):
            mydc.DrawLine(x, y, unit*dotnum, y)
            y=y+unit

#自定义应用程序对象          
class App(wx.App):
    def OnInit(self):
        #创建窗口对象
        frame = myFrame()
        frame.Show() 
        self.SetTopWindow(frame)

        if(frame.isEmptyChess) :    #判断是否是空棋盘，并进去棋局 ,计算，并下第一个黑子
            frame.isEmptyChess = 0  #不是开局了
            index = utl.pos()       #索引x,y
            index.x =  int((frame.dotnum-1)/2 )  #计算最中间的棋子
            index.y = int((frame.dotnum-1)/2 )
            frame.playChessByIndex(frame.whiteFlag ,index)  #下第一白子
            
        return True

    def OnExit(self):
        print('应用程序退出')
        return 0


